package main;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.commons.io.IOUtils;

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			final MyJFrame f = new MyJFrame();
			f.addWindowListener(new WindowAdapter() {
				public void windowClosing(WindowEvent e) {
					System.exit(0);
				}
			});
			final ServerSocket serverSocket = new ServerSocket(3237);
			Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {

				@Override
				public void run() {
					System.out.println("Shutting down...");
					if (serverSocket != null)
						try {
							serverSocket.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					System.out.println("Shutdown complete");
				}
			}));
			System.out.println("Port = " + serverSocket.getLocalPort());
			while (true) {
				final Socket client = serverSocket.accept();
				byte[] buffer = IOUtils.toByteArray(client.getInputStream());
				f.getContent().setData(buffer, buffer.length);
				f.getContent().paint(f.getGraphics());
				client.getOutputStream().write(1);
				client.getOutputStream().flush();
				client.getOutputStream().close();
				client.close();
			}
		} catch (Exception e) {
		}
	}
}
